//
//  RootViewController.m
//  暴走段子_王桂敏
//
//  Created by 王桂敏 on 15/6/9.
//  Copyright (c) 2015年 lanouhn. All rights reserved.
//

#import "RootViewController.h"
#import "DuanziViewController.h"
#import "SetupTableViewCell.h"
#import "SDWebImageManager.h"
#import "SDImageCache.h"
#import "RegAndLoginViewController.h"
#import "Define.h"
@interface RootViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>
@property (nonatomic,retain) UIImageView *backgroundImageView;
@property (nonatomic,retain) UITableView *tableView;
@property (nonatomic,retain) NSMutableArray *dataSource;
@property (nonatomic,retain) NSString *cacheSize;//缓存文件大小
@property (nonatomic,retain) UISlider *lightSlider;//亮度
@end

@implementation RootViewController
- (void)dealloc{
    [_backgroundImageView release];
    [_tableView release];
    [_dataSource release];
    [_cacheSize release];
    [_lightSlider release];
    [super dealloc];
}
- (UISlider *)lightSlider{
    if (!_lightSlider) {
        self.lightSlider = [[[UISlider alloc] initWithFrame:CGRectMake(75, 0, 80, 20)] autorelease];
        _lightSlider.maximumValue = 1;
        _lightSlider.minimumValue = 0.5;
        _lightSlider.value = 1;
        [_lightSlider addTarget:self action:@selector(handleLightSliderAction:) forControlEvents:UIControlEventValueChanged];
    }
    return _lightSlider;
}
- (void)handleLightSliderAction:(UISlider *)slider{
    [[NSNotificationCenter defaultCenter] postNotificationName:kLightChange object:nil userInfo:@{@"value":[NSNumber numberWithFloat:slider.value]}];
}

- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        self.dataSource = [NSMutableArray array];
        NSArray *imageNames = @[@"清除缓存",@"亮度",@"登录"];
        NSArray *names = @[@"缓存",@"亮度",@"版本"];
        for (int i = 0; i < imageNames.count; i++) {
            NSMutableArray *array = [NSMutableArray array];
            [array addObject:names[i]];
            [array addObject:imageNames[i]];
            [_dataSource addObject:array];
        }
    }
    return _dataSource;
}
- (UITableView *)tableView{
    if (!_tableView) {
        self.tableView = [[[UITableView alloc] initWithFrame:CGRectMake(0, 50, 180, kSCREENHEIGHT) style:UITableViewStylePlain] autorelease];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}
- (UIImageView *)backgroundImageView{
    if (!_backgroundImageView) {
//        self.backgroundImageView = [[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"anyUser.jpg"]] autorelease];
        self.backgroundImageView = [[UIImageView alloc] init];
        _backgroundImageView.backgroundColor =[UIColor orangeColor];
        _backgroundImageView.frame = CGRectMake(0, 0, 200, kSCREENHEIGHT);
        _backgroundImageView.alpha = 0.9;
        _backgroundImageView.userInteractionEnabled = YES;
    }
    return _backgroundImageView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    switch (indexPath.section) {
        case 0:
        {
            self.cacheSize = [NSString stringWithFormat:@"%0.1fM",[self folderSizeAtPath] / 1024 / 1024];
            UIAlertView *alerView = [[UIAlertView alloc] initWithTitle:@"提醒" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            alerView.message = [NSString stringWithFormat:@"%@缓存，是否清除缓存？",self.cacheSize];
            [alerView show];
            [self.view addSubview:alerView];
            [alerView release];
        }
            break;
        case 2:
        {
            UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:@"当前版本为4.0" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil] autorelease];
            [alert show];
            [self.view addSubview:alert];
        }
        default:
            break;
    }

}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        return;
    }
    [self clearCache];
    [self.tableView reloadData];

}

//获取缓存路径
- (NSString *)getCache{
    NSString *cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
    return cachePath;
}
- (NSString *)getDoc{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *docPath = paths.lastObject;

    return docPath;
}
//获取文件夹大小
- (CGFloat)folderSizeAtPath{
    //创建文件管理器
    NSFileManager *manager = [NSFileManager defaultManager];
    //获取文件夹路径
    NSString *folderPath = [self getCache];
    NSString *docPath = [self getDoc];
    //如果缓存文件不存在，就返回0
    if (![manager fileExistsAtPath:folderPath] && ![manager fileExistsAtPath:docPath]) {
        return 0;
    }

    NSString *fileName = nil;//定义一个空的文件名，用来获取枚举器中的文件名
    long long folderSize = 0;//定义并初始化文件大小为0

    if ([manager fileExistsAtPath:folderPath]) {
        //如果缓存文件存在就计算缓存文件的大小
        NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];//从缓存路径中的文件数组得到枚举器

        while ((fileName = [childFilesEnumerator nextObject]) != nil) {
            //得到单个文件的绝对路径
            NSString *fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
            //定义单个文件变量并初始化为0
            float singleFileSize = 0.0;
            //如果该单个文件存在，获取单个文件的大小
            if ([manager fileExistsAtPath:fileAbsolutePath]) {
                //attributesOfItemAtPath:获取文件的属性
                singleFileSize = [[manager attributesOfItemAtPath:fileAbsolutePath error:nil] fileSize];
            }
            folderSize += singleFileSize;
        }

    }

    if ([manager fileExistsAtPath:docPath]) {
        //如果缓存文件存在就计算缓存文件的大小
        NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:docPath] objectEnumerator];//从缓存路径中的文件数组得到枚举器

        while ((fileName = [childFilesEnumerator nextObject]) != nil) {
            //得到单个文件的绝对路径
            NSString *fileAbsolutePath = [docPath stringByAppendingPathComponent:fileName];
            //定义单个文件变量并初始化为0
            float singleFileSize = 0.0;
            //如果该单个文件存在，获取单个文件的大小
            if ([manager fileExistsAtPath:fileAbsolutePath]) {
                //attributesOfItemAtPath:获取文件的属性
                singleFileSize = [[manager attributesOfItemAtPath:fileAbsolutePath error:nil] fileSize];
            }
            folderSize += singleFileSize;
        }

    }
        return folderSize;
}
//清除缓存
- (void)clearCache{
    NSFileManager *manager = [NSFileManager defaultManager];
    NSString *floderPath = [self getCache];
    NSString *docPath = [self getDoc];
    if ([manager fileExistsAtPath:floderPath]) {
        NSArray *childFiles = [manager subpathsAtPath:floderPath];
        for (NSString *fileName in childFiles) {
            NSString *absolutePath = [floderPath stringByAppendingPathComponent:fileName];
            [manager removeItemAtPath:absolutePath error:nil];
        }
    }
    if ([manager fileExistsAtPath:docPath]) {
        NSArray *childFiles = [manager subpathsAtPath:docPath];
        for (NSString *fileName in childFiles) {
            NSString *absolutePath = [docPath stringByAppendingPathComponent:fileName];
            [manager removeItemAtPath:absolutePath error:nil];
        }
    }

    [[SDImageCache sharedImageCache] cleanDisk];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    [self.view addSubview:self.leftView];
    self.navigationController.navigationBar.barTintColor = [UIColor orangeColor];
    self.title = @"";
    self.view.backgroundColor = [UIColor clearColor];
    UILabel *naviTitleLable = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 44)];
    naviTitleLable.text = @"设置";
    naviTitleLable.textAlignment = NSTextAlignmentCenter;
    naviTitleLable.font = [UIFont systemFontOfSize:15];
    self.navigationItem.titleView = naviTitleLable;
    self.view = self.backgroundImageView;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 3;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 20;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, kSCREENWIDTH, 20)] autorelease];
    view.backgroundColor = [UIColor clearColor];
    return view;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 20;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;


    cell.imageView.image = [UIImage imageNamed:[NSString stringWithFormat:@"%@.jpg",self.dataSource[indexPath.section][1]]];

    cell.backgroundColor = [UIColor clearColor];
    cell.imageView.layer.cornerRadius = 10;
    cell.imageView.layer.masksToBounds = YES;
    if (indexPath.section == 0) {
         self.cacheSize = [NSString stringWithFormat:@"%0.1fM",[self folderSizeAtPath] / 1024 / 1024];
    } else {
        self.cacheSize = @"";
    }

    cell.textLabel.text = [NSString stringWithFormat:@"%@   %@",self.dataSource[indexPath.section][0],self.cacheSize];
    cell.textLabel.textColor = [UIColor whiteColor];
    cell.textLabel.font = [UIFont fontWithName:@"Helvetica-Bold" size:12];
    if (indexPath.section == 1) {
        [cell.contentView addSubview:self.lightSlider];
    }



    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    return cell;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
